#pragma once
#include <iostream>
#include <cstring>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>


#include "log.hpp"

Log lg;

#define defaultport 8080
int size = 1024;
std::string defaultip = "0.0.0.0";

class UdpServer
{
public:
    UdpServer(int sockfd = 0,uint16_t port = defaultport,std::string ip = defaultip)
    :sockfd_(sockfd),
    port_(port),
    ip_(ip)
    {}

    void Init()
    {
        sockfd_ = socket(AF_INET,SOCK_DGRAM,0);
        if(sockfd_ < 0)
        {
            lg(fatal,"Socket error,errno: %d,error: %s",errno,strerror(errno));
        }
        lg(info,"Socket Success");

        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = inet_addr(ip_.c_str());

        int n  = bind(sockfd_,(struct sockaddr*)&local,sizeof(local));
        if(n < 0)
        {
            lg(fatal,"Bind error,errno: %d ,errno: %s",errno,strerror(errno));
        }
        lg(info,"Bind Success");
    }
    void Run()
    {
        is_running_ = true;
        while(is_running_)
        {
            char inbuffer[size];
            struct sockaddr_in client;
            bzero(&client,sizeof(client));
            socklen_t clientSize = sizeof(client);
            ssize_t n = recvfrom(sockfd_,inbuffer,sizeof(inbuffer),0,(struct sockaddr*)&client,&clientSize);

            if(n < 0)
            {
                lg(warning,"recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            inbuffer[n] = 0;
            std::string Info = inbuffer;
            std::cout << Info << std::endl; 
            sendto(sockfd_,Info.c_str(),Info.size(),0,(struct sockaddr*)&client,sizeof(client)); 

        }
    }

    ~UdpServer()
    {
        if(sockfd_ > 0) close(sockfd_);
    }

private:
    int sockfd_;
    uint16_t port_;
    std::string ip_;
    bool is_running_ = false;

};